package mn.idax.exchange.otc.task;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import mn.idax.exchange.otc.constant.ReferenceExchageConstant;
import mn.idax.exchange.otc.util.HttpClientUtil;
import mn.idax.exchange.otc.util.JsonUtil;
import mn.idax.exchange.otc.util.LogUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Map;


/**
 * @Auther: .jension
 * @Time 2018.11.08 16:11
 * @Description:获取汇率定时任务 currencylayer  API
 * http://apilayer.net/api/live?access_key=f58b5d140dc038d87b43848dcf7ed023
 */
@Component
@Order(1)
@EnableScheduling
@Slf4j
public class ExchangeRateJob extends ReferenceExchageConstant implements ApplicationRunner {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Value("${exchange.rate}")
    private String RATE_API_URL;
    @Value("${exchange.key}")
    private String RATE_KEY;

    /**
     * 汇率
     */
    public static Map<String, Object> rateMap = Maps.newHashMap();

    @Override
    public void run(ApplicationArguments args) {
        execute();
    }

    @Scheduled(cron = "0 0 * * * ?")
    public void execute() {
        LogUtils.info(ExchangeRateJob.class, "ExchangeRateJob execute run start.");
        // 更新汇率
        updateRate();
        LogUtils.info(ExchangeRateJob.class, "ExchangeRateJob execute run end.");
    }

    /**
     * 更新法币：USD汇率
     */
    public void updateRate() {
        String exchangeRateApiResp = "";
        try {
            // 获取所有法币
            StringBuilder currencySb = new StringBuilder();
            // forEach函数实现内部迭代
            Arrays.asList(allCurrency).forEach(o -> {
                if (currencySb.length() > 0) {
                    currencySb.append(",");
                }
                currencySb.append(o);
            });

            exchangeRateApiResp = HttpClientUtil.doGet(RATE_API_URL + RATE_KEY + "&currencies=" + currencySb.toString());
            Map<String, Object> stringObjectMap = JsonUtil.readValue(exchangeRateApiResp, new TypeReference<Map<String, Object>>() {
            });
            // 请求失败获取redis汇率
            if (null == stringObjectMap || !(Boolean) stringObjectMap.get("success")) {
                // TODO 替补汇率获取
                stringObjectMap = JsonUtil.readValue(redisTemplate.opsForValue().get(REDIS_RATE_KEY), new TypeReference<Map<String, Object>>() {
                });
            } else {
                // 更新存储redis
                redisTemplate.opsForValue().set(REDIS_RATE_KEY, JSON.toJSONString(stringObjectMap));
            }
            rateMap.putAll((Map<String, Object>) stringObjectMap.get("rates"));

        } catch (Exception e) {
            LogUtils.error(ExchangeRateJob.class, "updateRate：USD汇率updateRate() error..{" + exchangeRateApiResp + "}" + ExceptionUtils.getStackTrace(e));

        }
    }

    /**
     * 汇率转换
     *
     * @param price
     * @param currencyTF
     */

    public static BigDecimal rateTransformation(BigDecimal price, String currencyTF) {
        log.info("currencyUSD:=================" + currencyUSD + currencyTF);
        Object o = rateMap.get(currencyUSD + currencyTF);
        if(o == null){
            return price;
        }
        return price.multiply(new BigDecimal(String.valueOf(o))).setScale(DECIMAL, BigDecimal.ROUND_DOWN);
    }

}
